package com.syyo.sso.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * @ author: wang
 * @ date: 2021/4/19 9:23
 * @ Description:
 */
@Controller
public class ClientSsoController {


    /**
     * 无需登录就可以访问
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }


    /**
     * 需登录才可以访问
     *
     * @param token 只要登录成功就会带上token
     */
    @GetMapping("/emps")
    public String emps(Model model, HttpSession session,
                       @RequestParam(value = "token", required = false) String token) {


        if (!StringUtils.isEmpty(token)) {
            // token不为空，表示是已登录的状态
            // 查询用户的信息
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://server1.com:8080/info?token=" + token;
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser", body);

        }

        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            // 没登录，跳转到登录服务器进行登录

            // 跳转过去，带上自己的当前的页面地址
            return "redirect:http://server1.com:8080/login.html?redirect_url=http://client1.com:8081/emps";

        } else {
            ArrayList<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }
    }
}
